package com.yc;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.IDN;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 单线程服务器
 * @author zwei
 * @create 2024-07-19 8:40
 */
public class Test4_talkServer {
    private static Logger logger = Logger.getLogger(Test4_talkServer.class.getName());

    public static void main(String[] args) throws IOException {
        //方案1：直接指定一个端口
        //方案二：循环10000已上的端口  试一个空闲的端口
        //方案3：将端口配置在一个  xml文件中
        final int port = 10000;
        ServerSocket ss = null;
        for (int i = port; i < 65535; i++) {
            try {
                //完成一台时间服务  选择合适端口的工作
                ss = new ServerSocket(i);
                logger.info("端口" + i + "空闲，使用该端口");
                break;
            } catch (Exception e) {
                if (e instanceof BindException) {
                    logger.info("端口" + i + "被占用");
                }
            }
        }
        System.out.println(ss.getInetAddress().getHostAddress()+"启动了，监听了端口号"+ss.getLocalPort());
        //客户端通过键盘录入聊天信息
        Scanner keyboard=new Scanner(System.in);
        while (true){
            //用了最新的try  resource 因为Socket，Scanner，PrintWriter都实现了CloSable，所以都可以放在try中 以自动关闭
            try (
                Socket s=ss.accept();
                //套接字流
                Scanner clientReader=new Scanner(s.getInputStream());   //Scanner.nextLine() 按n来读取
                PrintWriter pw=new PrintWriter(s.getOutputStream());    //PrintWriter.writeLine() --输出数据\n
            ){
                logger.info("客户端："+s.getRemoteSocketAddress()+"连接上来了");
                do{
                    String response=clientReader.nextLine();
                    System.out.println("客户端"+s.getRemoteSocketAddress()+"对server说："+response);
                    if ("bye".equalsIgnoreCase(response)){
                        System.out.println("客户端"+s.getRemoteSocketAddress()+"主动断开与服务器的连接");
                        break;
                    }
                    System.out.println("请输入服务器想对客户端"+s.getRemoteSocketAddress()+"说的话：");
                    String line=keyboard.nextLine();
                    pw.println(line);
                    pw.flush();
                    if ("bye".equalsIgnoreCase(line)){
                        System.out.println("服务器要求主动断开与客户端"+s.getRemoteSocketAddress()+"的连接");
                        break;
                    }
                }while (true);
                System.out.println("在服务端正常结束与客户端"+s.getRemoteSocketAddress()+"聊天。。。");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
